package mspbots.data.sync.rippling.receivers;

import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.data.sync.BaseReceiver;
import mspbots.data.sync.ResultMessageModel;
import mspbots.data.sync.rippling.model.RipplingCompanyDeductions;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.Optional;

/**
 * @author Jay Yang
 */
@Log4j2
@Component
@RequiredArgsConstructor
public class RipplingCompanyDeductionsReceiver extends BaseReceiver {

    //    @RabbitListener(queues = "rippling.company_deductions.sync")   数据为空,根据数据再编写
    public void processCompanyDeductions(ResultMessageModel model) {
        log.debug("processCompanyDeductions[rippling.company_deductions.sync] ResultMessageModel {}", model);
        if (ResultMessageModel.MessageModelAction.ADD.equals(model.getAction())) {
            JsonNode deductionsNode = model.getEntity();
            RipplingCompanyDeductions deductions = this.objectMapper.convertValue(deductionsNode, RipplingCompanyDeductions.class);
            deductions.setExtend(deductionsNode);
            deductions.setTenantId(model.getTenantId());
            deductions.setSyncTime(model.getSendTime());

            Optional<Long> id = this.databaseClient.execute("select id from rippling_company_deductions " +
                    "where tenant_id =:tenantId and other_id =:otherId")
                    .as(Long.class)
                    .bind("tenantId", deductions.getTenantId())
                    .bind("otherId", deductions.getOtherId())
                    .fetch().one().blockOptional(Duration.ofSeconds(10));

            if (id.isPresent() && id.get() > 0) {
                deductions.setId(id.get());
                this.databaseClient.update().table(RipplingCompanyDeductions.class).using(deductions).fetch().rowsUpdated().subscribe();
            } else {
                this.databaseClient.insert().into(RipplingCompanyDeductions.class).using(deductions).fetch().rowsUpdated().subscribe();
            }

        }
    }
}
